// useSecureStore.js
import { useState, useEffect } from "react";
import * as SecureStore from "expo-secure-store";

const useSecureStore = (key: string) => {
    const [data, setData] = useState<null | string>(null);
    const [error, setError] = useState<null | any>(null);
    useEffect(() => {
        // 获取数据
        const fetchData = async () => {
            try {
                const storedData = await SecureStore.getItemAsync(key);
                setData(storedData);
            } catch (error) {
                setError(error);
            }
        };

        fetchData(); // 在组件挂载时执行一次

        // 清理 effect
        return () => {
            setData(null);
            setError(null);
        };
    }, [key]); // 当 key 发生变化时重新执行

    // 存储数据
    const saveData = async (value: string) => {
        try {
            await SecureStore.setItemAsync(key, value);
            setData(value);
            setError(null);
        } catch (error) {
            setError(error);
        }
    };

    // 删除数据
    const deleteData = async () => {
        try {
            await SecureStore.deleteItemAsync(key);
            setData(null);
            setError(null);
        } catch (error) {
            setError(error);
        }
    };

    return { data, error, saveData, deleteData };
};

export default useSecureStore;
